package com.owc.service.impl.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.dao.VersionMapper;
import com.owc.domain.BaseResult;
import com.owc.domain.PageVo;
import com.owc.domain.dto.admin.VersionDTO;
import com.owc.domain.entity.Version;
import com.owc.domain.vo.admin.VersionVo;
import com.owc.service.admin.VersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Jackies
 * @Date 2019/12/18 22:52
 * @Description TODO://
 **/
@Slf4j
@Service
public class VersionServiceImpl implements VersionService {

	@Resource
	private VersionMapper versionMapper;

	@Override
	public Boolean addVersion(VersionVo versionVo) {
		try {
			versionMapper.insert(versionVo.converterTo());
		} catch (Exception e) {
			log.error("保存新版本失败 e:{}",e.getMessage());
			throw new BadRequestException(ExceptionEnum.UNKNOWN_ERR);
		}
		return true;
	}

	@Override
	public BaseResult<List<VersionDTO>> list(PageVo pageVo) {

		List<VersionDTO> versionDTOS = new ArrayList<>();

		PageHelper.startPage(pageVo.getPageIndex(),pageVo.getPageSize());
		List<Version> versions = versionMapper.selectList();
		PageInfo<Version> pageInfo = new PageInfo<>(versions);

		if(versions == null || versions.isEmpty()){
			return BaseResult.success(new ArrayList<>());
		}

		versions.forEach(version -> {
			versionDTOS.add(new VersionDTO().convertFrom(version));
		});

		return BaseResult.success(versionDTOS,pageInfo.getTotal());
	}

	@Override
	public VersionDTO detail(Long id) {

		Version version = versionMapper.selectByPrimaryKey(id);
		if(version == null){
			return null;
		}
		return new VersionDTO().convertFrom(version);
	}
}
